package it.mouseclient;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

import touchpad.TouchpadHandler;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

public class TouchpadActivity extends Activity {

	private UDPClient client;
	private boolean logged;

	private TouchpadHandler touchHandler;

	private String mPassword;
	private String mIPAddress;
	private int mPort;

	private Bundle mBundle;

	private UserLoginTask mAuthTask;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_touchpad);

		// ottengo il tcp client dalla login activity (che ha avviato questa
		// activity)
		Intent intent = getIntent();
		String pkg = getPackageName() + ".";
		mBundle = intent.getBundleExtra(pkg + R.string.connection_param_id);
		getConnectionParam(mBundle);

		findViewById(R.id.relativeLayout).setOnTouchListener(
				new OnTouchListener() {

					@Override
					public boolean onTouch(View v, MotionEvent event) {
						if (touchHandler != null && logged)
							new AsyncTask<MotionEvent, Void, Boolean>() {

								@Override
								protected Boolean doInBackground(
										MotionEvent... params) {

									return touchHandler.checkCommand(params[0]);
								}

								@Override
								protected void onPostExecute(
										final Boolean success) {
									if (!success)
										finish();
								}
							}.execute(event);

						return true;
					}
				});

	}

	@Override
	protected void onStart() {
		super.onStart();
		mAuthTask = new UserLoginTask();
		mAuthTask.execute((Void) null);
	}

	@Override
	protected void onStop() {
		super.onStop();
		if (client!=null){
			// Disconnetto il client
			new DisconnectTask().execute((Void) null);
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		// String pkg = getPackageName() + ".";
		// outState.putBundle(pkg + R.string.connection_param_id, mBundle);
	}

	@Override
	protected void onRestoreInstanceState(Bundle outState) {
		super.onRestoreInstanceState(outState);
		// String pkg = getPackageName() + ".";
		// mBundle=outState.getBundle(pkg+R.string.connection_param_id);
		// getConnectionParam(mBundle);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_touchpad, menu);
		// listener sul menu item "disconnect"
		menu.getItem(0).setOnMenuItemClickListener(
				new OnMenuItemClickListener() {

					@Override
					public boolean onMenuItemClick(MenuItem item) {
						// Disconnetto il client
						new DisconnectTask().execute((Void) null);

						return true;
					}
				});

		return true;
	}

	private void getConnectionParam(Bundle b) {
		String pkg = getPackageName() + ".";
		mPassword = b.getString(pkg + R.string.password_id);
		mIPAddress = b.getString(pkg + R.string.address_id);
		mPort = b.getInt(pkg + R.string.port_id);
	}

	private boolean connect() {
		boolean c = false;
		try {
			client = new UDPClient(InetAddress.getByName(mIPAddress), mPort);
			client.open();
			c = true;
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return c;
	}

	public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
		@Override
		protected Boolean doInBackground(Void... params) {
			// TODO: attempt authentication against a network service.
			if (connect()) {
				logged = client.doLogin(mPassword);
				return logged;
			} else
				return false;
		}

		@Override
		protected void onPostExecute(final Boolean success) {
			mAuthTask = null;

			if (success) {
				touchHandler = new TouchpadHandler(client);
			} else {
				finish();
			}
		}

		@Override
		protected void onCancelled() {
			mAuthTask = null;

		}
	}

	/**
	 * Represents an asynchronous login/registration task used to authenticate
	 * the user.
	 */
	public class DisconnectTask extends AsyncTask<Void, Void, Boolean> {
		@Override
		protected Boolean doInBackground(Void... params) {
			client.close(true);
			return true;
		}

		@Override
		protected void onPostExecute(final Boolean success) {

			if (success) {
				finish();
			}
		}
	}

}
